<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/19
 * Time: 11:06
 */
namespace app\admin\controller;

use app\admin\model\FinanceModel;
use app\admin\model\OrderModel;
use app\admin\model\MemberModel;
use app\admin\model\DepartmentModel;
use app\admin\model\ProductModel;
use app\admin\controller\Department;
use think\Db;
use think\Request;
use app\admin\model\RoleModel;//samsara 2018-8-1 新增

class Finance extends Base{
		//调用当前用户下的部门 13 -21
		public function _initialize(){
			parent::_initialize();
			$uid = session('id');
			if (empty(session('can_see')[0])) {
				$department_id =Db::name('department')->where(['pid'=>0])->value('id');
			}else{
				$role_id = Db::name('user')->where(['id'=>$uid])->value('role_id');
				$department_id =Db::name('role')->where(['id'=>$role_id])->value('department_id');
			}
			$roleModel = new RoleModel();
			$departUserID = $roleModel->getUsersByDepartIdCansee($department_id);
			$where['id'] = array('in',$departUserID);
			//查询当前部门下的所有职员
			$departUserArr = Db::name('user')->field(['id','real_name'])->where($where)->select();
			$myArr = Db::name('department')->where('id',$department_id)->find();
			$dep_Arr = $this->DeparArr($department_id);


			$myArr['children'] = $dep_Arr;
			$departArr[0] = $myArr;
			$option = $this->arr2Tree($departArr);
			$this->assign([
				'dep_Arr' 		=> $option,
				'departUserArr' => $departUserArr,
				'id' 			=> $uid
			]);
		}
		public function arr2Tree($arr,$option='',$strk = ''){
			$str = '| - ';
			foreach($arr as $v){
				$option .= '<option value="'.$v['id'].'">'.$str.$strk.$v['name'].'</option>';
				if(!empty($v['children'])){
					$strk .= '- - ';
					$option = $this->arr2Tree($v['children'],$option,$strk);
					$strk = mb_substr($strk,4,mb_strlen($strk));
				}
			}
			return $option;
		}

		public function DeparArr($id){
			$arr= [];
			$departArr = Db::name('department')->where('pid',$id)->select();
			foreach ($departArr as $key => $value){
				$value['children'] = $this->DeparArr($value['id']);
				$arr[] = $value;
			}
			return $arr;
		}

		// public function getMydeparts ($id){
		// 	$departModel = new DepartmentModel();
		// 	$arr = $departModel->getSonsByPid($id);
		// 	$brr = [];
		// 	foreach($arr as $v){
		// 		array_push($brr,DB::name('department')->where('id',$v['id'])->find());
		// 	}
		// 	print_r($brr);die;
		// 	return getTree($brr);
		// }

		public function getDepartArr(){
			$uid = session('id');
			if (empty(session('can_see')[0])) {
				$department_id =Db::name('department')->where(['pid'=>0])->value('id');
			}else{
				$role_id = Db::name('user')->where(['id'=>$uid])->value('role_id');
				$department_id =Db::name('role')->where(['id'=>$role_id])->value('department_id');
			}
			$myArr = Db::name('department')->where('id',$department_id)->find();
			$dep_Arr = $this->DeparArr($department_id);
			$myArr['children'] = $dep_Arr;
			$departArr[0] = $myArr;
			return json(msg(1, $departArr, 'ok'));
		}
		//Ajax 获取选择部门的职员信息
		public function departUser(){
			$depart_id = input('post.depart_id');
			// $roleModel = new RoleModel();
			$finance = new Finance();
			$departUserID = $finance->getAllRolesAndAllUsersByParentDepart($depart_id);
			// print_r($departUserID);die;
			$where['id'] = array('in',$departUserID['userArr']);
			//查询当前部门下的所有职员
			$departUserArr = Db::name('user')->where($where)->field(['id','real_name'])->select();
			return json(['code'=>1,'data'=>$departUserArr]);
		}
	/**
     * 财务管理
     * 黄
     * 18-04-19
     */
     public function index ()
     {

     }
     //订单录入
     public function orderInput (){
         $m_id = input('param.m_id');
         if (isset($m_id)) {
             //查看当前用户的订单信息
             $or_where['m_id'] = $m_id;
             //2018-7-19 samsara 增 订单默认状态[status]
             $or_where['status'] = ['in',[1,4]];
             $orderArr = Db::name('order')->where($or_where)->order('id desc')->find();
             if(!empty($orderArr)){
                 $orderArr['payment_methodN'] = Db::name('product_attr')->where(['id'=>$orderArr['payment_method']])->value('name');
                 $orderArr['phone'] = Db::name('member')->where(['id'=>$m_id])->value('phone');
								 $orderArr['pay_typeN'] = Db::name('member_attr')->where(['id'=>$orderArr['pay_type']])->value('name');
                 $orderModel = new OrderModel();
                 $orderInfo = $orderModel->getProductInfo($orderArr['id']);
                 $orderArr['cofigArr'] = $orderInfo['cofigArr'][0];//产品配置
                 $proList = $orderModel->getProductList($orderArr['school_id'],$orderArr['major_id']);//产品列表
                 $this->assign([
                     'orderArr' => $orderArr,
                     'proList' => $proList
                 ]);
             }
             $member = new MemberModel();
             $returnMsg = $member->getOneMember($m_id);
             $this->assign([
                 'orderArr'  => $orderArr,
                 'returnMsg' => $returnMsg
             ]);
             // dump($returnMsg);
             // return $this->fetch();
         }
 		    //支付方式
         $payTypeArr = Db::name('member_attr')->where(['pid'=>10])->select();
         //生源途径
         $source_origin = Db::name('member_attr')->where(['pid'=>32])->select();
     		$this->assign([
     			'payTypeArr' => $payTypeArr,
     			'source_origin' => $source_origin
     		]);
         return $this->fetch();
     }
 	/**
 	 * 读取客户
 	 */
 	 public function memList(){
 		 if (request()->isAjax()) {
          $param = input('param.');
          $limit = $param['pageSize'];
          $offset = ($param['pageNumber'] - 1) * $limit;
          $where = [];
          if (!empty($param['name'])) {
              $where['name'] = ['like', '%' . $param['name'] . '%'];
          }
          if (!empty($param['phone'])) {
              $where['phone'] = ['like', '%' . $param['phone'] . '%'];
          }
   			 $creaArr = Db::name('user')->column('id');
   			 $where['create_uid'] = array('in',$creaArr);
   			 $where['delete_status'] = array('neq',2);//是否是伪删除
    			 $where['status'] = array('neq',8);//客户状态不能是释放状态
    			 $where['share'] = array('neq',1);//客户状态不能是分享状态
    			 $where['first_relation'] = array('neq',0);//客户不能是公共客户
          $member = new MemberModel();
          $selectResult = $member->getMemberByWhere($where, $offset, $limit);
          $return['total'] = $member->getAllMember($where);  // 总数据
          $return['rows'] = $selectResult;
          return json($return);
       }
       return $this->fetch();
 	 }
     /**
 	 *订单列表
 	 */
     public function businOrder (){
         if (request()->isAjax()) {
             $param = input('param.');
             $limit = $param['pageSize'];
             $offset = ($param['pageNumber'] - 1) * $limit;
             $where = [];
       			if(!empty($param['stu_name'])){
       				$where['stu_name'] = ['like', '%' . $param['stu_name'] . '%'];
       			}
       			if(!empty($param['order_sn'])){
       				$where['order_sn'] = ['like', '%' . $param['order_sn'] . '%'];
       			}
       			if(!empty($param['school_id'])){
       				$where['school_id'] = $param['school_id'];
       			}
       			$where['delete_status'] = array('neq',1);
             $order = new OrderModel();
             $selectResult = $order->orderListForFin($where, $offset, $limit);
             foreach($selectResult as &$vo){
                 $vo['stu_name'] = '<a href="'.url('member/memberInfo',['m_id'=>$vo['m_id']]).'">'.$vo['stu_name'].'</a>';
                 $vo['gradeN'] = Db::name('product_attr')->where(['id'=>$vo['grade']])->value('name');//层次
                 $vo['systemN'] = Db::name('product_attr')->where(['id'=>$vo['system']])->value('name');//学制
                 $vo['acquisition_modeN'] = Db::name('product_attr')->where(['id'=>$vo['acquisition_mode']])->value('name');//授课模式
                 $vo['payment_methodN'] = Db::name('product_attr')->where(['id'=>$vo['payment_method']])->value('name');//缴费方式
         				$vo['pay_typeN'] = Db::name('member_attr')->where(['id'=>$vo['pay_type']])->value('name');
         				// 创建时间
         				$vo['c_time'] = date('Y-m-d',$vo['c_time']);
                 switch ($vo['status']){
                     case 0:
                         $vo['statusN'] = '已取消';
                         break;
                     case 1:
                         $vo['statusN'] = '进行中';
                         $vo['operate'] = showOperate($this->makeButton1($vo['id']));
                         break;
                     case 2:
                         $vo['statusN'] = '已完成';
                         $vo['operate'] = showOperate($this->makeButton1($vo['id']));
                         break;
                     case 3:
                         $vo['statusN'] = '退款';
                         break;
                     case 4:
                         $vo['statusN'] = '创建中';
                         $vo['operate'] = showOperate($this->makeButton2($vo['m_id'],$vo['id']));
                         break;
           					default:
           						  $vo['statusN'] = '创建中';
                         $vo['operate'] = showOperate($this->makeButton2($vo['m_id'],$vo['id']));
                 }
             }

             $return['total'] = $order->getAllOrder($where);  // 总数据
             $return['rows'] = $selectResult;
             return json($return);
         }
     		//学校列表
     		$schoolArr = Db::name('school_specialty')->where(['pid'=>0])->select();
     		$this->assign([
     			'schoolArr' => $schoolArr
     		]);
         return $this->fetch();
     }
     /**
 	 * 发起退款
 	 */
     public function Gathering (){
     		$param = input('param.');
     		if ($param['deleteNum'] < 0){
     			return msg(-1, '', '金额输入错误');
     		}
         $order = new OrderModel();
         $gather_status = $order->getGathering($param);
         return $gather_status;
     }

 	/**
 	 * 删除订单
 	 * @param $id
 	 * @return status
 	 */
 	public function deleteOrder (){
 		$param = $_POST['param'];
 		$member = new OrderModel();
 		$returnMsg = $member->delOrder($param);
 		return $returnMsg;
 	}
   /**
    * Ajax 请求
    * 修改订单状态
    */
    public function suerOrder(){
       $order_id = input('post.order_id');
       $orderArr = Db::name('order')->where(['id'=>$order_id])->find();
       $param['order_id'] = $order_id;//订单ID

       $where['id'] = $orderArr['m_id'];//客户ID
       $where['status'] = 7;//修改客户状态为成交状态
       $memberModel = new MemberModel;
       $order = new Order;
       $king = $memberModel->memberEdit($where);
       if ($king['code'] == 1) {
           $flag = $order->orderAdd($param);
           return $flag;
       }else {
           return json(msg($king['code'], $king['data'], $king['msg']));
       }
    }
    /**
     * Ajax 请求
     * 费用收取
     */
     public function total_many(){
         $param = input();
         $order = new Order;
         $flag = $order->orderAdd($param);
         return $flag;
     }
   /**
    * 拼装操作按钮
    * @param $id 跟踪记录
    * @return array
    */
     private function makeButton1($id){
         return [
             '费用收取' => [
                 'auth' => 'member/memberedit',
                 'href' => 'javascript:total_many('.$id.')',
                 'btnStyle' => 'success',
                 'icon' => 'fa fa-paste',
             ],
             '发起退款' => [
                 'auth' => 'member/memberedit',
                 'href' => 'javascript:deleteOre('.$id.')',
                 'btnStyle' => 'danger',
                 'icon' => 'fa fa-paste',
             ]
         ];
     }
     private function makeButton2($m_id,$id){
         return [
             '确认订单' => [
                 'auth' => 'member/memberedit',
                 'href' => 'javascript:sureOrder('.$id.')',
                 'btnStyle' => 'success',
                 'icon' => 'fa fa-paste',
             ],
             '修改订单' => [
                 'auth' => 'member/memberedit',
                 'href' => url('member/memberedit', ['id' => $m_id]).'#test=55',
                 'btnStyle' => 'success',
                 'icon' => 'fa fa-paste',
             ]
         ];
     }

/*黄*/
#-----------------------------------------------------------------------------------------------#
/**
 * [财务流水列表]
 */
public function accList (){
	$FincModel = new FinanceModel();
	if(request()->isAjax()){
		$param = input('param.');
		$limit = $param['pageSize'];
		$offset = ($param['pageNumber'] - 1) * $limit;
		$where = ['delete_status' => 0];
		$sortName = input('sortName');
		$sortOrder = input('sortOrder');
		$orderBy = $sortName." ".$sortOrder;
		$this->WhereSn($param['seaSn'],$FincModel);
		$this->WhereName($param['seaName'],$FincModel);
		$this->WhereSource($param['seaSource'],$FincModel);
		$this->WhereStatus($param['seaStatus'],$FincModel);
		$this->WhereTime($param['seaTime'],$FincModel);
		$this->WhereSchool($param['seaSchool'],$FincModel);
		$this->WhereMajor($param['seaMajor'],$FincModel);
		$this->WhereGradeID($param['seaGrade'],$FincModel);
		$this->WhereAsker($param['seaAsker'],$FincModel);
		$this->WhereAsk_D($param['seaAsk_D'],$FincModel);
		$this->WhereFee($param['seaFee'],$FincModel);
		$this->WhereBatchMember($param['seaBatch_member'],$FincModel);
		$return['rows'] = $FincModel->getInfoByWhere($where,true,$offset,$limit,$orderBy);
		$this->WhereSn($param['seaSn'],$FincModel);
		$this->WhereName($param['seaName'],$FincModel);
		$this->WhereSource($param['seaSource'],$FincModel);
		$this->WhereStatus($param['seaStatus'],$FincModel);
		$this->WhereTime($param['seaTime'],$FincModel);
		$this->WhereSchool($param['seaSchool'],$FincModel);
		$this->WhereMajor($param['seaMajor'],$FincModel);
		$this->WhereGradeID($param['seaGrade'],$FincModel);
		$this->WhereAsker($param['seaAsker'],$FincModel);
		$this->WhereAsk_D($param['seaAsk_D'],$FincModel);
		$this->WhereFee($param['seaFee'],$FincModel);
		$this->WhereBatchMember($param['seaBatch_member'],$FincModel);
		$return['total'] = $FincModel->getInfoByWhere($where);
		$return['rows'] = $this->translateFince($return['rows']);
		$return['sum'] = 0;
		foreach($return['rows'] as $k => $v){
			$return['sum'] += $v['total_amount'];
		}
		return $return;
	}
	$proModel = new ProductModel();
	$this->assign([
		'CanseeSchool' => $proModel->getCanseeSchool(),
		'grade_opt' => DB::name('product_attr')->where('pid',1)->select()
	]);
	return $this->fetch();
}
// 搜单号
public function WhereSn($param,$FincModel){
	$FincModel->where(function($query)use($param){
		if($param){
			$query->whereOr(['order_sn'=>["like","%".$param."%"]]);
			$query->whereOr(['account_sn'=>["like","%".$param."%"]]);
		}
	});
}
// 搜名称
public function WhereName($param,$FincModel){
	$st = DB::name('member')->where('name','like',"%".$param."%")->field('id')->select();
	$staff = DB::name('user')->where('real_name','like',"%".$param."%")->field('id')->select();
	foreach($staff as $v){
		array_push($st,$v);
	}
	$st = array_merge(array_filter($st));
	if(empty($st)){
		$FincModel->where('s_id',-999);
	}else{
		$FincModel->where(function($query)use($st){
			foreach($st as $k => $v){
				$query->whereOr('s_id',$v['id']);
				$query->whereOr('m_id',$v['id']);
			}
		});
	}
}
// 搜来源
public function WhereSource($param,$FincModel){
	if($param != ''){
		$FincModel->where('source',$param);
	}
}
// 搜状态
public function WhereStatus($param,$FincModel){
	if($param != ''){
		$FincModel->where('status',$param);
	}
}
// 搜时间(流水操作list)
public function WhereTime($param,$FincModel){
	if($param != ''){
		$start_time = strtotime(explode(" - ",$param)[0]);
		$end_time = strtotime(explode(" - ",$param)[1]);
		$FincModel->whereTime('finish_time','between',[$start_time,$end_time]);
	}
}
// 搜时间(统计)
public function WhereTimeReport($param,$FincModel){
	if($param != ''){
		$start_time = strtotime(explode(" - ",$param)[0]." 00:00:00");
		$end_time = strtotime(explode(" - ",$param)[1]." 23:59:59");
		$FincModel->whereTime('receivables_time','between',[$start_time,$end_time]);
	}
}
// 搜学校
public function WhereSchool($param,$FincModel){
	if($param != ''){
		$FincModel->where('s_role',0);
		$orderSnArr = DB::name('order')->where('school_id',$param)->column('order_sn');
		if(!empty($orderSnArr)){
			$FincModel->where(function($query)use($orderSnArr){
				foreach($orderSnArr as $v){
					$query->whereOr('order_sn',$v);
				}
			});
		}else{
			$FincModel->where('order_sn','-1');
		}
	}
}
// 搜专业
public function WhereMajor($param,$FincModel){
	if($param != ''){
		$FincModel->where('s_role',0);
		$orderSnArr = DB::name('order')->where('major_id',$param)->column('order_sn');
		if(!empty($orderSnArr)){
			$FincModel->where(function($query)use($orderSnArr){
				foreach($orderSnArr as $v){
					$query->whereOr('order_sn',$v);
				}
			});
		}else{
			$FincModel->where('order_sn','-1');
		}
	}
}
// 搜层次
public function WhereGrade($param,$FincModel){
	if($param != ''){
		$FincModel->where('s_role',0);
		$gradeSnArr = DB::name('product_attr')->where('pid',1)->where('name','like','%'.$param.'%')->column('id');
		if(empty($gradeSnArr)){
			$orderSnArr[0] = -1;
		}else{
			$orderSnArr = DB::name('order')->where(function($query)use($gradeSnArr){
				foreach($gradeSnArr as $v){
					$query->whereOr('grade',$v);
				}
			})->column('order_sn');
		}
		$FincModel->where(function($query)use($orderSnArr){
			foreach($orderSnArr as $v){
				$query->whereOr('order_sn',$v);
			}
		});
	}
}
//搜层次ID
public function WhereGradeID($param,$FincModel){
	if($param != ''){
		$FincModel->where('s_role',0);
		$gradeSnArr = DB::name('product_attr')->where('pid',1)->where('id',$param)->column('id');
		if(empty($gradeSnArr)){
			$orderSnArr[0] = -1;
		}else{
			$orderSnArr = DB::name('order')->where(function($query)use($gradeSnArr){
				foreach($gradeSnArr as $v){
					$query->whereOr('grade',$v);
				}
			})->column('order_sn');
		}
		$FincModel->where(function($query)use($orderSnArr){
			foreach($orderSnArr as $v){
				$query->whereOr('order_sn',$v);
			}
		});
	}
}
// 搜咨询师
public function WhereAsker($param,$FincModel){
	if($param != ''){
		$FincModel->where('s_role',0);
		// $AskArr = DB::name('user')->where('real_name','like','%'.$param.'%')->column('id');
		$AskArr = [$param];
		if(empty($AskArr)){
			$orderSnArr[0] = -1;
		}else{
			$orderSnArr = DB::name('order')->where(function($query)use($AskArr){
				foreach($AskArr as $v){
					$query->whereOr('first_relation',$v);
					$query->whereOr('second_relation',$v);
				}
			})->column('order_sn');
		}
		$FincModel->where(function($query)use($orderSnArr){
			foreach($orderSnArr as $v){
				$query->whereOr('order_sn',$v);
			}
		});
	}
}
// 搜咨询师部门
public function WhereAsk_D($param,$FincModel){
	if($param != ''){
		$FincModel->where('s_role',0);
		$res = $this->getAllRolesAndAllUsersByParentDepart($param);
		$rollArr = $res['rollArr'];
		$AskArr = $res['userArr'];
		if(empty($rollArr) || empty($AskArr)){
			$orderSnArr[0] = -1;
		}else{
			$orderSnArr = DB::name('order')->where(function($query)use($AskArr){
				foreach($AskArr as $v){
					$query->whereOr('first_relation',$v);
					$query->whereOr('second_relation',$v);
				}
			})->column('order_sn');
		}
		if(empty($orderSnArr)){
			$orderSnArr[0] = -1;
		}
		$FincModel->where(function($query)use($orderSnArr){
			foreach($orderSnArr as $v){
				$query->whereOr('order_sn',$v);
			}
		});
	}
}
// 搜四种费用
public function WhereFee($param,$FincModel){
	if($param != ''){
		$FincModel->where('s_role',0);
		$FincModel->where($param,'<>','0');
	}
}
// 搜批次
public function WhereBatch($param,$FincModel){
	if($param != ''){
		$FincModel->where('s_role',0);
		$stArr = DB::name('student')->where('batch','like','%'.$param.'%')->column('id');
		$FincModel->where(function($query)use($stArr){
			foreach($stArr as $v){
				$query->whereOr('s_id',$v);
			}
		});
	}
}

// 搜批次(member)
public function WhereBatchMember($param,$FincModel){
	if($param != ''){
		$FincModel->where('s_role',0);
		$stArr = DB::name('order')->where('batch','like','%'.$param.'%')->column('order_sn');
		$FincModel->where(function($query)use($stArr){
			foreach($stArr as $v){
				$query->whereOr('order_sn',$v);
			}
		});
	}
}
/**
 * [通过高级部门id获取所有子部门的角色id和用户id]
 */
public function getAllRolesAndAllUsersByParentDepart($param){
	$DepartModel = new DepartmentModel();
	$DepartCtrl = new Department();
	$departArr = $DepartModel->getSonsByPid($param);
	//推入自己
	array_push($departArr,['id'=>$param]);
	$rollArr = [];
	foreach($departArr as $k => $v){
		$rollArr[] = DB::name('role')->where('department_id',$v['id'])->column('id');
	}
	//2D to 1D
	$arr = [];
	foreach($rollArr as $v){
		foreach($v as $val){
			$arr[] = $val;
		}
	}
	$rollArr = $arr;
	$userArr = DB::name('user')->where(function($query)use($rollArr){
		foreach($rollArr as $v){
			$query->whereOr('role_id',$v);
		}
	})->column('id');
	$result = [
		'rollArr' => $rollArr,
		'userArr' => $userArr
	];
	return $result;
}

/**
 * [财务流水信息补充]
 */
public function translateFince($param){
	foreach($param as $k => $v){
		if($v['status'] == 0){
			$param[$k]['status_name'] = "<span class='span-danger'>未支付</span>";
		}elseif($v['status'] == 1 && $v['source'] != 3){
			$param[$k]['status_name'] = "<span class='span-primary'>已支付</span>";
		}elseif($v['status'] == 1 && $v['source'] == 3){
			$param[$k]['status_name'] = "<span class='span-danger'>已退款</span>";
		}elseif($v['status'] == 2){
			$param[$k]['status_name'] = "<span class='span-info'>已逾期</span>";
		}elseif($v['status'] == 3){
			$param[$k]['status_name'] = "<span class='span-warning'>已拒绝</span>";
		}elseif($v['status'] == 4){
			$param[$k]['status_name'] = "<span class='span-success'>已同意</span>";
		}elseif($v['status'] == 5){
			$param[$k]['status_name'] = "<span class='span-gray'>已取消</span>";
		}elseif($v['status'] == 6){
			$param[$k]['status_name'] = "<span class='span-gray'>坏账</span>";
		}
		switch ($v['source']) {
			case '0':$param[$k]['source_name'] = '学员';break;
			case '1':$param[$k]['source_name'] = '报销';break;
			case '2':$param[$k]['source_name'] = '罚款';break;
			case '3':$param[$k]['source_name'] = '<span class="span-danger">退款<span>';break;
			case '4':$param[$k]['source_name'] = '其他';break;
			default:$param[$k]['source_name'] = '学员';break;
		}
		$param[$k]['agent_name'] = DB::name('user')->where('id',$v['agent'])->value('real_name');
		// 咨询师及其部门
		$memberInfo = DB::name('member')->where('id',$v['m_id'])->find();
		$first = DB::name('user')->where('id',$memberInfo['first_relation'])->find();
		$second = DB::name('user')->where('id',$memberInfo['second_relation'])->find();
		$first_d = DB::name('role')->where('id',$first['role_id'])->value('department_id');
		$second_d = DB::name('role')->where('id',$second['role_id'])->value('department_id');
		$departModel = new DepartmentModel();
		$param[$k]['first'] = $first['real_name'];
		$param[$k]['second'] = $second['real_name'];
		$param[$k]['first_depart'] = $departModel->getTotalDepartStr($first_d);
		$param[$k]['second_depart'] = $departModel->getTotalDepartStr($second_d);
		// 支付方式、生源途径
		$param[$k]['pay_type'] = DB::name('order')->alias('order')
			->join('member_attr attr','order.pay_type = attr.id')
			->where('order.order_sn',$v['order_sn'])
			->value('attr.name');
		$param[$k]['origin'] = DB::name('member')->alias('member')
			->join('member_attr attr','member.source_origin = attr.id')
			->where('member.id',$v['m_id'])
			->value('attr.name');

		// 时间
    if($v['receivables_time'] == 0){
      $param[$k]['receivables_time'] = '';
    }else{
      $param[$k]['receivables_time'] = date("Y-m-d",$v['receivables_time']);
    }
		if(date("m",$v['finish_time']) == date("m",time())){
			$param[$k]['finish_time'] = date("Y-",$v['finish_time'])
									  . '<span class="span-danger span-strong">'
									  . date("m",$v['finish_time']) .'</span>'
									  . date("-d",$v['finish_time']);
		}else{
			$param[$k]['finish_time'] = date("Y-m-d",$v['finish_time']);
		}

		//姓名 学校专业、部门
		if($v['s_role'] == 1){
			$param[$k]['name'] = DB::name('user')->where('id',$v['s_id'])->value('real_name');
			$role_id = DB::name('user')->where('id',$v['s_id'])->value('role_id');
			$depart_id = DB::name('role')->where('id',$role_id)->value('department_id');
			$depart = $departModel->getTotalDepartStr($depart_id);
			$param[$k]['from_s'] = $depart;
			$param[$k]['from_m'] = '';
			$param[$k]['from'] = $depart;
		}else{
			$st = DB::name('student')->where('id',$v['s_id'])->find();
			if(empty($st)){
				$st['batch'] = '';
			}
			$order = DB::name('order')->where('order_sn',$v['order_sn'])->find();
			if($order){
				$st['name'] = $order['stu_name'];
				$st['school'] = $order['school'];
				$st['major'] = $order['major'];
				$st['grade'] = $order['grade'];
			}
			$param[$k]['name'] = $st['name'];
			$param[$k]['from_s'] = $st['school'];
			$param[$k]['from_m'] = $st['major'];
			$param[$k]['from'] = $st['school'].'-'.$st['major'];
			$param[$k]['grade'] = DB::name('product_attr')->where('id',$st['grade'])->value('name');
			$param[$k]['batch'] = $st['batch'];
			$param[$k]['batch_member'] = DB::name('order')->where('order_sn',$v['order_sn'])->value('batch');
		}
		$accTotal = $v['tuition'] + $v['registration'] + $v['material_cost'] + $v['photo_collection'];
		$accTotal == 0 ? $accTotal = $v['total_amount'] : $accTotal = $accTotal;
		if($accTotal < 0){
			$param[$k]['total_amount_name'] = '<span class="span-danger">'.$accTotal.'</span>';
		}else{
			$param[$k]['total_amount_name'] = $accTotal;
		}
		// 操作按钮
		// status:0.未支付,1已支付/退款,2已逾期,3.已拒绝, 4.同意,5已取消
		// source:0.学费 1.报销 2.罚款 3.退款 4.其他
		switch ($v['status']) {
			case '0':
				if($v['source'] != 3){
					$param[$k]['operate'] = '<a class="btn btn-sm btn-primary" href="javascript:receivables('.$v["id"].');">收款</a>';
				}else{
					$param[$k]['operate'] = '<span class="span-warning">等待授权</span>';
					$param[$k]['auth'] = '<a class="btn btn-sm btn-success" href="javascript:authRefund('.$v["id"].');">授权</a>';
				}break;
			case '4':
				if($v['source'] == 3){
					$param[$k]['operate'] = '<a class="btn btn-sm btn-danger" href="javascript:receivables('.$v["id"].');">退款</a>';
					$param[$k]['auth'] = DB::name('user')->where('id',$v['auth'])->value('real_name');
				}else{
					$param[$k]['operate'] = '';
				}break;
			case'1':
				$param[$k]['operate'] = '';
				$param[$k]['auth'] = DB::name('user')->where('id',$v['auth'])->value('real_name');
				break;
			case'2':$param[$k]['operate'] = '';break;
			case'3':
				$param[$k]['operate'] = '';
				$param[$k]['auth'] = DB::name('user')->where('id',$v['auth'])->value('real_name');
				break;
			case'5':
				$param[$k]['operate'] = '';
				$param[$k]['auth'] = DB::name('user')->where('id',$v['auth'])->value('real_name');
				break;
			default:$param[$k]['operate'] = '';break;
		}
		if($v['source'] == 0 || $v['source'] == 4){
			$param[$k]['print'] = ' <a class="btn btn-sm btn-success" href="javascript:AccPrint('.$v["id"].');"><i class="fa fa-print"></i></a>';
		}else{
			$param[$k]['print'] = "";
		}

	}
	return $param;
}

/**
 * [伪删除教务流水]
 */
public function delAccount(){
	$param = input('post.');
	$idArr = explode(",",$param['ids']);
	$FincModel = new FinanceModel();
	return $FincModel->delAccount($idArr);
}

/**
 * [财务收款]
 */
public function receivables(){
	$param = input('post.');
	$acc_id = $param['id'];
	$accInfo = DB::name('account')->where('id',$acc_id)->find();
	$source = $accInfo['source'];
	switch ($source) {
		// case'1':return $this->receivables_1($accInfo);break;// 报销
		// case'2':return $this->receivables_2($accInfo);break;// 罚款
		case'3':return $this->receivables_3($accInfo);break;// 退款
		case'0':return $this->receivables_0($accInfo);break;// 学费
		default:return $this->receivables_4($accInfo);break;// 其他
	}
}
/**
 * [学费收款]
 * 1.该订单流水状态变成已收款
 * 2.(如果未支付订单数 == 分期数)读取客户信息写入学员
 * 3.(如果已支付订单数+1 == 分期数)更改订单状态为已完成
 * 4.修改order agent 字段为session（'id'）
 * 5.修改收款时间receivables_time 为 time()
 */
public function receivables_0($accInfo){
	$FincModel = new FinanceModel();
	$MbInfo = DB::name('member')->where('id',$accInfo['m_id'])->find();
	$MbInfo['birthday'] = strtotime($MbInfo['birthday']);
	if($MbInfo['sex']==1 || $MbInfo['sex']=="男"){
		$MbInfo['sex'] = 1;
	}else{
		$MbInfo['sex'] = 2;
	}
	$OrderInfo = DB::name('order')->where('order_sn',$accInfo['order_sn'])->find();
	// 是否新建学员
	$count = $FincModel->getInfoByWhere([
		'order_sn' => $accInfo['order_sn'],
		'status' => 0,
		'source' => 0,
		'delete_status' => 0
	]);
	$payment = DB::name('account')->where('order_sn',$accInfo['order_sn'])->count();
	$count == $payment ? $is_save = true : $is_save = false;
	// 订单是否已经完成
	$count_1 = $FincModel->getInfoByWhere([
		'order_sn' => $accInfo['order_sn'],
		'status' => 1
	]);
	($count_1 + 1 == $payment) ? $is_over = true : $is_over = false;

	$StData = [
		'name' => $MbInfo['name'],
		'm_id' => $MbInfo['id'],
		'phone' => $MbInfo['phone'],
		'consultant' => $MbInfo['first_relation'],
		'school' => $OrderInfo['school'],
		'school_id' => $OrderInfo['school_id'],
		'major' => $OrderInfo['major'],
		'major_id' => $OrderInfo['major_id'],
		'grade' => $OrderInfo['grade'],
		'school_roll' => 1,
		'school_date' => time(),
		'id_photo' => $MbInfo['id_photo'],
		'id_photo_url' => $MbInfo['id_photo_url'],
		'nation' => $MbInfo['nation'],
		'birthday' => $MbInfo['birthday'],
		'id_card' => $MbInfo['id_card'],
		'sex' => $MbInfo['sex'],
		'batch' => $OrderInfo['batch']
	];
	DB::startTrans();
	try{
		$FincModel->setAccStatus($accInfo['id'],1);
		if($is_save){
			$st_id = DB::name('student')->insertGetId($StData);
			DB::name('account')->where('order_sn',$accInfo['order_sn'])->update(['s_id'=>$st_id]);
		}
		if($is_over){
			DB::name('order')->where('order_sn',$accInfo['order_sn'])->update(['status'=>1]);
		}
		DB::commit();
		return ['code'=>1,'msg'=>'收款成功'];
	}catch(\Exception $e){
		DB::rollback();
		return ['code'=>0,'msg'=>'收款失败'.$e->getMessage()];
	}
}
/**
 * [报销单收款]
 */
// public function receivables_1($accInfo){
// 	print_r($accInfo);
// }
/**
 * [罚款单收款]
 */
// public function receivables_2($accInfo){
// 	print_r($accInfo);
// }

/**
 * [退款单收款]
 * 1.更新order.status = 3;order.update_time = time();
 * 2.更新同订单号的流水abnormal = 1;
 * 3.更新同订单号的未支付的且来源为学费的流水的status = 5;update_time = time();agent = session('id');
 * 4.更新account.status = 1;update_time = time();agent = session('id'),;
 */
public function receivables_3($accInfo){
	DB::startTrans();
	try{
		DB::name('order')->where('order_sn',$accInfo['order_sn'])->update([
			'status' => 3,
			'update_time' => time()
		]);
		DB::name('account')->where('order_sn',$accInfo['order_sn'])->update([
			'abnormal' =>1
		]);
		DB::name('account')->where(['order_sn'=>$accInfo['order_sn'],'source'=>0,'status'=>0])->update([
			'status' => 5,
			'update_time' => time(),
			'agent' => session('id')
		]);
		DB::name('account')->where('id',$accInfo['id'])->update([
			'status' => 1,
			'update_time' => time(),
			'agent' => session('id'),
			'receivables_time' => time()
		]);
		DB::commit();
		return ['code'=>1,'msg'=>'退款成功'];
	}catch(\Exception $e){
		DB::rollback();
		return ['code'=>0,'msg'=>'退款失败:'.$e->getMessage()];
	}
}
/**
 * [其他单收款]
 */
public function receivables_4($accInfo){
	$FincModel = new FinanceModel();
	DB::startTrans();
	try{
		$FincModel->setAccStatus($accInfo['id'],1);
		DB::commit();
		return ['code'=>1,'msg'=>'收款成功'];
	}catch(\Exception $e){
		DB::rollback();
		return ['code'=>0,'msg'=>'收款失败'.$e->getMessage()];
	}
}

/**
 * [添加报销单]
 */
public function addExpense(){
	if($this->request->isPost()){
		$param = input('post.');
		$FincModel = new FinanceModel();
		$result = $this->validate($param,'AccountValidate');
		if($result !== true){
			return ['code'=>0,'msg'=>'录入失败:'.$result];
		}
		$data = [
			's_id' => $param['s_id'],
			's_role' => 1,
			'total_amount' => ($param['total_amount'] * -1),
			'remarks' => $param['remarks'],
			'status' => 1,
			'c_time' => time(),
			'finish_time' => time(),
			'receivables_time' => time(),
			'source' => 1,
			'create_uid' => session('id'),
			'agent' => session('id')
		];
		return $FincModel->addExpense($data);
	}
	return $this->fetch();
}

/**
 * [添加罚款单]
 */
public function addTicket(){
	if($this->request->isPost()){
		$param = input('post.');
		$FincModel = new FinanceModel();
		$result = $this->validate($param,'AccountValidate');
		if($result !== true){
			return ['code'=>0,'msg'=>'录入失败:'.$result];
		}
		$data = [
			's_id' => $param['s_id'],
			's_role' =>  $param['s_role'],
			'total_amount' => $param['total_amount'],
			'remarks' => $param['remarks'],
			'status' => 1,
			'c_time' => time(),
			'finish_time' => time(),
			'source' => 2,
			'receivables_time' => time(),
			'create_uid' => session('id'),
			'agent' => session('id')
		];
		if($data['s_role'] == 0){
			$data['m_id'] = DB::name('student')->where('id',$param['s_id'])->value('m_id');
		}
		return $FincModel->addExpense($data);
	}
	$proModel = new ProductModel();
	$this->assign([
		'CanseeSchool' => $proModel->getCanseeSchool(),
	]);
	return $this->fetch();
}

/**
 * [同意/拒绝退款]
 */
public function authRefund(){
	$param = input('post.');
	$param['agree'] == 1 ? $state = 4 : $state = 3 ;
	$id = $param['acc_id'];
	$orderSn = DB::name('account')->where('id',$id)->value('order_sn');
	$orderInfo = DB::name('order')->where('order_sn',$orderSn)->find();
	$orderStatus = ($orderInfo['status'] -30);
	if($state == 3){
		$result = DB::name('order')->where('order_sn',$orderSn)->update(['status' => $orderStatus,'update_time'=>time()]);
		if($result === false){
			return ['code'=>0,'msg'=>'退款授权失败'];
		}
	}
	$FincModel = new FinanceModel();
	return $FincModel->authAccount($id,$state);
}

	/**
	 * [财务统计]
	 */
	public function statistics(){
		if($this->request->isPost()){
			$FincModel = new FinanceModel();
			$param = input('post.');
			//确定时间段和步长
			if(!empty($param['time_slot'])){
				$time_slot_arr = explode(" - ",$param['time_slot']);
				$start_time = strtotime($time_slot_arr[0])." 00:00:00";
				$end_time = strtotime($time_slot_arr[1])." 23:59:59";
			}else{
				$start_time = strtotime(date("Ymd",strtotime('-1 month'))."000000");
				$end_time = strtotime(date("Ymd",time())."235959");
			}
			if(empty($param['time_step'])){
				$time_step = 1 * 24 *3600;//时间步长默认为1天
			}else{
				if(!preg_match("/^\d*$/",$param['time_step']) || $param['time_step']<=0){
					return ['code'=>0,'msg'=>'时间步长输入有误'];
				}
				$time_step = $param['time_step'] * 24 * 3600;
			}
			$pointNum = ceil(($end_time - $start_time) / $time_step);
			$Xdata = [];
			$redData = [];
			$bluData = [];
			for($i=0;$i<=$pointNum;$i++){
				$a = $start_time + $i * $time_step;//第i个时间
				array_push($Xdata,date("Y-m-d",($a)));
				if($i == 0){
					$redData[$i] = 0;
					$sum =  DB::name("account")
						 ->where(['status'=>1,'delete_status'=>0,'total_amount'=>['<',0]])
						 ->whereTime('receivables_time','between',[$start_time - $i * $time_step,$a])
						 ->select();
					foreach($sum as $v){
						$redData[$i] += $v['total_amount']+$v['tuition']+$v['registration']+$v['material_cost']+$v['photo_collection'];
					}
					$redData[$i] *= -1;
					$bluData[$i] = 0;
					$sum = DB::name("account")
					 	 ->where(['status'=>1,'delete_status'=>0,'total_amount'=>['>=',0]])
					 	 ->whereTime('receivables_time','between',[$start_time - $i * $time_step,$a])
					 	 ->select();
					foreach($sum as $v){
 						$bluData[$i] += $v['total_amount']+$v['tuition']+$v['registration']+$v['material_cost']+$v['photo_collection'];
 					}
				}else{
					$redData[$i] = 0;
					$sum = DB::name("account")
						 ->where(['status'=>1,'delete_status'=>0,'total_amount'=>['<',0]])
						 ->whereTime('receivables_time','between',
						 	[
								strtotime(date('Ymd',strtotime($Xdata[$i-1]))."235959"),
								strtotime(date("Ymd",$a)."235959")
							]
						 )->select();
					foreach($sum as $v){
 						$redData[$i] += $v['total_amount']+$v['tuition']+$v['registration']+$v['material_cost']+$v['photo_collection'];
 					}
					$redData[$i] *= -1;
					$bluData[$i] = 0;
					$sum  = DB::name("account")
						 ->where(['status'=>1,'delete_status'=>0,'total_amount'=>['>=',0]])
						 ->whereTime('receivables_time','between',
						 	[
								strtotime(date('Ymd',strtotime($Xdata[$i-1]))."235959"),
								strtotime(date("Ymd",$a)."235959")
							]
						 )->select();
					foreach($sum as $v){
 						$bluData[$i] += $v['total_amount']+$v['tuition']+$v['registration']+$v['material_cost']+$v['photo_collection'];
 					}
				}
			}
			$pieData[0]['name'] = "学员";
			$pieData[0]['value'] = $this->ForPieData($start_time,$end_time,0);
			$pieData[1]['name'] = "报销";
			$pieData[1]['value'] = $this->ForPieData($start_time,$end_time,1);
			$pieData[2]['name'] = "罚款";
			$pieData[2]['value'] = $this->ForPieData($start_time,$end_time,2);
			$pieData[3]['name'] = "退款";
			$pieData[3]['value'] = $this->ForPieData($start_time,$end_time,3);
			$pieData[4]['name'] = "其他";
			$pieData[4]['value'] = $this->ForPieData($start_time,$end_time,4);

			return ['code'=>1,'msg'=>'图表加载成功','Xdata' => $Xdata,'redData'=>$redData,'bluData'=>$bluData,'pieData'=>$pieData];
		}
		$proModel = new ProductModel();
		$this->assign([
			'CanseeSchool' => $proModel->getCanseeSchool(),
			'grade_opt' => DB::name('product_attr')->where('pid',1)->select()
		]);
		return $this->fetch();
	}

	public function getMajorByPid(){
		$pid = input('post.pid');
		$proModel = new ProductModel();
		$data = $proModel->getMajorByPid($pid);
		return ['code'=>1,'msg'=>'','data'=>$data];
	}

	public function ForPieData($start_time,$end_time,$source){
		if($source == 0){
			$money = 0;
			$info = DB::name("account")
					 ->where(['status'=>1,'delete_status'=>0,'source'=>$source])
					 ->whereTime('receivables_time','between',[$start_time,$end_time])
					 ->select();
			foreach($info as $v){
				$money += $v['tuition'] + $v['registration'] + $v['material_cost'] + $v['photo_collection'];
			}
		}else{
			$money =  DB::name("account")
					 ->where(['status'=>1,'delete_status'=>0,'source'=>$source])
					 ->whereTime('receivables_time','between',[$start_time,$end_time])
					 ->sum('total_amount');
		}
		if($money < 0){
			$money *= -1;
		}
		return $money;
	}
	/**
	 * [财务报表]
	 */
	 public function accReportList (){
 		$FincModel = new FinanceModel();
		/*
		// 离散收款时间
        $start_time = strtotime("2018-05-01");
        $end_time = strtotime("2018-05-10");

        $num = DB::name('account')->where('status',1)->count();
        if($num == 0){
            return ['code'=>0,'msg'=>'表中没有数据'];
        }
        $step = abs($end_time - $start_time) / $num;//步长

        DB::startTrans();
        try {
            $k = 1;// id起始
            for($i = $start_time;$i <= $end_time; $i += $step){
                DB::name('account')->where('id',$k)->update(['receivables_time'=>$i]);
                $k ++ ;
            }
            Db::commit();
            return ['code'=>1,'msg'=>'成功'];
        } catch (Exception $e) {
            Db::rollback();
            return ['code'=>0,'msg'=>'失败'.$e];
        }
		*/
 		if(request()->isAjax()){
 			$param = input('param.');
 			$where = ['delete_status' => 0];
 			$sortName = input('sortName');
 			$sortOrder = input('sortOrder');
			if(empty($param['seaTime'])){
				$param['seaTime'] = date("Y-m-d")." - ".date("Y-m-d");
			}
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;
			$orderBy = $sortName." ".$sortOrder;
			$this->WhereSn($param['seaSn'],$FincModel);
			$this->WhereName($param['seaName'],$FincModel);
			$this->WhereSource($param['seaSource'],$FincModel);
			$this->WhereStatus($param['seaStatus'],$FincModel);
			$this->WhereTimeReport($param['seaTime'],$FincModel);
			$this->WhereSchool($param['seaSchool'],$FincModel);
			$this->WhereMajor($param['seaMajor'],$FincModel);
			$this->WhereGradeID($param['seaGrade'],$FincModel);
			$this->WhereAsker($param['seaAsker'],$FincModel);
			$this->WhereAsk_D($param['seaAsk_D'],$FincModel);
			$this->WhereFee($param['seaFee'],$FincModel);
			$this->WhereBatch($param['seaBatch'],$FincModel);
			$return['rows'] = $FincModel->getInfoByWhere($where,true,$offset,$limit,$orderBy);
			$this->WhereSn($param['seaSn'],$FincModel);
			$this->WhereName($param['seaName'],$FincModel);
			$this->WhereSource($param['seaSource'],$FincModel);
			$this->WhereStatus($param['seaStatus'],$FincModel);
			$this->WhereTimeReport($param['seaTime'],$FincModel);
			$this->WhereSchool($param['seaSchool'],$FincModel);
			$this->WhereMajor($param['seaMajor'],$FincModel);
			$this->WhereGradeID($param['seaGrade'],$FincModel);
			$this->WhereAsker($param['seaAsker'],$FincModel);
			$this->WhereAsk_D($param['seaAsk_D'],$FincModel);
			$this->WhereFee($param['seaFee'],$FincModel);
			$this->WhereBatch($param['seaBatch'],$FincModel);
			$return['total'] = $FincModel->getInfoByWhere($where);
			$return['rows'] = $this->translateFince($return['rows']);
			$return['sum'] = 0;
			$return['tuition_sum'] = 0;
			$return['registration_sum'] = 0;
			$return['material_cost_sum'] = 0;
			$return['photo_collection_sum'] = 0;
			foreach($return['rows'] as $k => $v){
				$return['tuition_sum'] += $v['tuition'];
				$return['registration_sum'] += $v['registration'];
				$return['material_cost_sum'] += $v['material_cost'];
				$return['photo_collection_sum'] += $v['photo_collection'];
				$accTotal = $v['tuition'] + $v['registration'] + $v['material_cost'] + $v['photo_collection'];
				$accTotal == 0 ? $accTotal = $v['total_amount'] : $accTotal = $accTotal;
				$return['sum'] += $accTotal;
			}
			return $return;
 		}
 		return $this->fetch();
 	}

	/**
	 * [财务统计总表]
	 */
	public function accReportTotal(){
		if(request()->isAjax()){
 			$param = input('param.');
			if(empty($param['seaTime'])){
				$start_time = date("Y")."-01-01 00:00:00";
				$end_time = date('Y').'-12-31 23:59:59';
			}else{
				$start_time = $param['seaTime']."-01-01 00:00:00";
				$end_time = $param['seaTime'].'-12-31 23:59:59';
			}
			$start_time_l = strtotime($start_time);
			$end_time_l = strtotime($end_time);
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;

			// 组合专业、层次、批次(搜索)
			if($param['seaSchool']){
				$major = DB::name('school_specialty')->where('pid',$param['seaSchool'])->select();
			}else{
				$major = DB::name('school_specialty')->where('pid','<>',0)->select();
			}
			if($param['seaMajor']){
				$major = DB::name('school_specialty')->where('id',$param['seaMajor'])->select();
			}
			if($param['seaGrade']){
				$grade = DB::name('product_attr')->where('id',$param['seaGrade'])->select();
			}else{
				$grade = DB::name('product_attr')->where('pid',1)->select();
			}
			if($param['seaBatch']){
				$batch = DB::name('student')->where('batch','like',"%".$param['seaBatch']."%")->column('batch');
			}else{
				$batch = DB::name('student')->column('batch');
			}

			$batch = array_unique($batch);
			$arr = [];
			foreach($major as $k => $v){
				foreach($grade as $ke => $va){
					foreach($batch as $key =>  $val){
						$arr[] = $v['id'].'-'.$va['id'].'-'.$val;
					}
				}
			}

			// 分页数组
			$initarr = [];
			$j = 0;
			for($i = $offset; $i < ($limit+$offset); $i++ ){
				if(isset($arr[$i])){
					$initarr[$j]['major'] = explode('-',$arr[$i])[0];
					$initarr[$j]['grade'] = explode('-',$arr[$i])[1];
					$initarr[$j]['batch'] = explode('-',$arr[$i])[2];
				}
				$j++;
			}

			$initwhere = [
				'delete_status' => 0,
				'status' => 1,
				'source'=>0,
				's_role'=>0,
			];
			$initData = [];
			$acc= [];
			foreach($initarr as $k => $v){
				$order = DB::name('order')->where([
					'major_id' => $v['major'],
					'grade' => $v['grade']
				])->column('order_sn');
				if(empty($order)){
					$order[] = -1;
				}
				$batch = DB::name('student')->where('batch',$v['batch'])->column('id');
				$use['order'] = $order;
				$use['batch'] = $batch;
				$use['start_time'] = $start_time_l;
				$use['end_time'] = $end_time_l;
				$db = $this->initDB($use,$initwhere);
				$acc[$k]['tuition'] = $db->sum('tuition');
				$db = $this->initDB($use,$initwhere);
				$acc[$k]['registration'] = $db->sum('registration');
				$db = $this->initDB($use,$initwhere);
				$acc[$k]['material_cost'] = $db->sum('material_cost');
				$db = $this->initDB($use,$initwhere);
				$acc[$k]['photo_collection'] = $db->sum('photo_collection');
				$acc[$k]['total'] = $acc[$k]['tuition']+$acc[$k]['registration']+$acc[$k]['material_cost']+$acc[$k]['photo_collection'];
				$majorInfo = DB::name('school_specialty')->where('id',$v['major'])->find();
				$acc[$k]['major_name'] = $majorInfo['name'];
				$acc[$k]['school_name'] = DB::name('school_specialty')->where('id',$majorInfo['pid'])->value('name');
				$acc[$k]['year'] = date("Y",$start_time_l);
				$acc[$k]['grade'] = DB::name('product_attr')->where('id',$v['grade'])->value('name');
				$acc[$k]['people_num'] = DB::name('student')->where([
					'major_id' => $v['major'],
					'batch' => $v['batch'],
					'grade' => $v['grade']
				])->count();
				$acc[$k]['major_id'] = $v['major'];
				$acc[$k]['grade_id'] = $v['grade'];
				$acc[$k]['batch'] = $v['batch'];
			}
			$people_num = 0;
			$tuition_sum = 0;
			$registration_sum = 0;
			$material_cost_sum = 0;
			$photo_collection_sum = 0;
			$total_money_sum = 0;
			foreach($acc as $k => $v){
				$people_num += $v['people_num'];
				$tuition_sum += $v['tuition'];
				$registration_sum += $v['registration'];
				$material_cost_sum += $v['material_cost'];
				$photo_collection_sum += $v['photo_collection'];
				$total_money_sum += $v['total'];
			}
			$return['rows'] = $acc;
			$return['people_num'] = $people_num;
			$return['tuition_sum'] = $tuition_sum;
			$return['registration_sum'] = $registration_sum;
			$return['material_cost_sum'] = $material_cost_sum;
			$return['photo_collection_sum'] = $photo_collection_sum;
			$return['total_money_sum'] = $total_money_sum;
			$return['total'] = sizeof($arr);
			return $return;
 		}
 		return $this->fetch();
	}

	public function initDB($use,$initwhere){
		$db = DB::name('account')->where($initwhere)->where(function($query)use($use){
			foreach($use['order'] as $v){
				$query->whereOr('order_sn',$v);
			}
		})->where(function($query)use($use){
			foreach($use['batch'] as $v){
				$query->whereOr('s_id',$v);
			}
		})->whereTime('receivables_time','between',[$use['start_time'],$use['end_time']]);
		return $db;
	}

	/**
	 * [打印收据]
	 */
	public function AccPrint(){
		$acc_id = input('get.acc_id');
		$FincModel = new FinanceModel;
		$accInfo = DB::name('account')->where('id',$acc_id)->find();
		$orderInfo = DB:: name('order')->where('order_sn',$accInfo['order_sn'])->find();
		$stInfo = DB:: name('student')->where('id',$accInfo['s_id'])->find();
		if($stInfo['sex'] == 0){
			$sex = "保密";
		}elseif($stInfo['sex'] == 1){
			$sex = "男";
		}else{
			$sex = "女";
		}
		$agent = DB::name('user')->where('id',$accInfo['agent'])->value('real_name');
		$writer = DB::name('user')->where('id',session('id'))->value('real_name');
		$first_relation = DB::name('user')->where('id',$orderInfo['first_relation'])->value('real_name');
		$role_id = DB::name('user')->where('id',$orderInfo['first_relation'])->value('role_id');
		$depart_id = DB::name('role')->where('id',$role_id)->value('department_id');
		$depart = DB::name('department')->where('id',$depart_id)->value('name');
		$grade = DB::name('product_attr')->where('id',$orderInfo['grade'])->value('name');
		$acquisition_mode = DB::name('product_attr')->where('id',$orderInfo['acquisition_mode'])->value('name');
		$pay_type = DB::name('member_attr')->where('id',$orderInfo['pay_type'])->value('name');
		$source_origin = DB::name('member')->alias('member')
						->join('member_attr attr','member.source_origin = attr.id')
						->where('member.id',$accInfo['m_id'])
						->value('attr.name');
		vendor("Num2Rmb.Num2Rmb");
		$toRmb = new \Num2Rmb();
		$everyTotal = $accInfo['tuition']+$accInfo['registration']+$accInfo['material_cost']+$accInfo['photo_collection'];
		$bigMoney = $toRmb->changeToRmb($everyTotal);
		$this->assign([
			'accInfo' => $accInfo,
			'orderInfo' => $orderInfo,
			'stInfo' => $stInfo,
			'sex' => $sex,
			'agent' => $agent,
			'writer' => $writer,
			'first_relation' => $first_relation,
			'depart' => $depart,
			'grade' => $grade,
			'acquisition_mode' => $acquisition_mode,
			'bigMoney' => $bigMoney,
			'everyTotal' => $everyTotal,
			'markIn' => '支付方式:'.$pay_type."\n".'生源途径:'.$source_origin."\n".'批次:'.$orderInfo['batch']
		]);
		return $this->fetch();
	}

	/**
	 * [待处理流水]
	 */
	public function pendbill(){
		$FincModel = new FinanceModel();
		if(request()->isAjax()){
			$param = input('param.');
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;
			$where = ['delete_status'=>0,'source'=>0];
			$FincModel->where(function($query)use($param){
				$query->whereOr('status',2);
				$query->whereOr('status',5);
				$query->whereOr('status',6);
			});
			$sortName = input('sortName');
			$sortOrder = input('sortOrder');
			$orderBy = $sortName." ".$sortOrder;
			$this->WhereSn($param['seaSn'],$FincModel);
			$this->WhereName($param['seaName'],$FincModel);
			$this->WhereStatus($param['seaStatus'],$FincModel);
			$this->WhereTime($param['seaTime'],$FincModel);
			$return['rows'] = $FincModel->getInfoByWhere($where,true,$offset,$limit,$orderBy);
			$FincModel->where(function($query)use($param){
				$query->whereOr('status',2);
				$query->whereOr('status',5);
				$query->whereOr('status',6);
			});
			$this->WhereSn($param['seaSn'],$FincModel);
			$this->WhereName($param['seaName'],$FincModel);
			$this->WhereStatus($param['seaStatus'],$FincModel);
			$this->WhereTime($param['seaTime'],$FincModel);
			$return['total'] = $FincModel->getInfoByWhere($where);
			$return['rows'] = $this->translateFince($return['rows']);
			foreach($return['rows'] as $k => $v){
				$return['rows'][$k]['operation'] = '';
				if(authCheck('finance/receivables') && $v['status'] != 5){
					$return['rows'][$k]['operation'] .= '<a class="btn btn-sm btn-primary" href="javascript:receivables('.$v['id'].');">收款</a>';
				}
				if(authCheck('finance/acccancel') && $v['status'] != 5){
					$return['rows'][$k]['operation'] .= ' <a class="btn btn-sm btn-warning" href="javascript:accCancel('.$v['id'].');">取消</a>';
				}
			}
			return $return;
		}
		return $this->fetch();
	}
	/**
	 * [取消该订单]
	 */
	public function accCancel(){
		$id = input('post.id');
		DB::startTrans();
		try{
			$orderSn = DB::name('account')->where('id',$id)->value('order_sn');
			DB::name('account')->where('order_sn',$orderSn)->update(['status'=>5,'agent'=>session('id')]);
			DB::name('order')->where('order_sn',$orderSn)->update(['status'=>0]);
			DB::commit();
			return ['code'=>1,'msg'=>'操作成功'];
		}catch(\Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'操作失败：'.$e->getMessage()];
		}
	}
	/**
	 * [导出全部数据]
	 */
	public function ExpotrAllFinanceInfo(){
		$res = DB::name('account')->where(['status'=>1,'delete_status'=>0])->select();
		$res = $this->translateFince($res);
		$data = [];
		foreach($res as $k => $v){
			$data[$k]['id'] = $v['id'];
			$data[$k]['account_sn'] = $v['account_sn'];
			$data[$k]['order_sn'] = $v['order_sn'];
			$data[$k]['source_name'] = $v['source_name'];
			$data[$k]['name'] = $v['name'];
			$data[$k]['from'] = $v['from'];
			$data[$k]['grade'] = $v['grade'];
			$data[$k]['from_m'] = $v['from_m'];
			$data[$k]['batch'] = $v['batch'];
			$data[$k]['receivables_time'] = $v['receivables_time'];
			$data[$k]['first'] = $v['first'];
			$data[$k]['first_depart'] = $v['first_depart'];
			$data[$k]['second'] = $v['second'];
			$data[$k]['second_depart'] = $v['second_depart'];
			$data[$k]['pay_type'] = $v['pay_type'];
			$data[$k]['origin'] = $v['origin'];
			$data[$k]['tuition'] = $v['tuition'];
			$data[$k]['registration'] = $v['registration'];
			$data[$k]['material_cost'] = $v['material_cost'];
			$data[$k]['photo_collection'] = $v['photo_collection'];
			$data[$k]['total_amount_name'] = $v['total_amount_name'];
		}
		$savePath = explode('../application/',APP_PATH)[0].'upload/excel/';
		$title = [
			'ID',
			'订单单号',
			'流水单号',
			'来源',
			'学员/报销人',
			'学校/部门',
			'层次',
			'专业',
			'批次',
			'付款时间',
			'咨询师1',
			'咨询师1部门',
			'咨询师2',
			'咨询师2部门',
			'支付方式',
			'生源途径',
			'学费',
			'报名费',
			'资料费',
			'照片采集费',
			'总金额'
		];
		$this->exportExcel($title,$data, 'download', $savePath, false);
	}

	/**
	 * 数据导出
	 * @param array $title   标题行名称
	 * @param array $data   导出数据
	 * @param string $fileName 文件名
	 * @param string $savePath 保存路径
	 * @param $type   是否下载  false--保存   true--下载
	 * @return string   返回文件全路径
	 * @throws PHPExcel_Exception
	 * @throws PHPExcel_Reader_Exception
	 */
	function exportExcel($title=[], $data=[], $fileName='', $savePath='./', $isDown=true){
		vendor("PHPExcel.Classes.PHPExcel");
		vendor("PHPExcel.Classes.PHPExcel.IOFactory");
		$obj = new \PHPExcel();

		//横向单元格标识
		$cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

		$obj->getActiveSheet(0)->setTitle('sheet名称');   //设置sheet名称
		$_row = 1;   //设置纵向单元格标识
		if($title){
			$_cnt = count($title);
			$obj->getActiveSheet(0)->mergeCells('A'.$_row.':'.$cellName[$_cnt-1].$_row);   //合并单元格
			$obj->setActiveSheetIndex(0)->setCellValue('A'.$_row, '数据导出：'.date('Y-m-d H:i:s'));  //设置合并后的单元格内容
			$_row++;
			$i = 0;
			foreach($title AS $v){   //设置列标题
				$obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);
				$i++;
			}
			$_row++;
		}

		//填写数据
		if($data){
			$i = 0;
			foreach($data AS $_v){
				$j = 0;
				foreach($_v AS $_cell){
					$obj->getActiveSheet(0)->setCellValue($cellName[$j] . ($i+$_row), $_cell);
					$j++;
				}
				$i++;
			}
		}

		//文件名处理
		if(!$fileName){
	        $fileName = uniqid(time(),true);
	    }
		$_fileName = iconv("utf-8", "gb2312", $fileName);   //转码
		$_fileName = $_fileName.session('id').'.xls';
		$objWrite = \PHPExcel_IOFactory::createWriter($obj, 'Excel5');
		$_savePath = $savePath.$_fileName;

		if($isDown){   //网页下载
			header("Pragma: public");
			header("Expires: 0");
			header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
			header("Content-Type:application/force-download");
			header("Content-Type:application/vnd.ms-execl");
			header("Content-Type:application/octet-stream");
			header("Content-Type:application/download");
			header('Content-Disposition:attachment;filename='.$_fileName);
			header("Content-Transfer-Encoding:binary");
			$objWrite->save('php://output');
		}else{
			$objWrite->save($_savePath);
		}
		#释放内存
		unset($objWrite);
		unset($obj);
		return $_savePath;
	}

	public function num_price_statistics(){
		if($this->request->isPost()){
			$param = input('post.');
			if(empty($param['seaTime'])){
				$start_time = date("Y")."-01-01 00:00:00";
				$end_time = date('Y').'-12-31 23:59:59';
			}else{
				$start_time = $param['seaTime']."-01-01 00:00:00";
				$end_time = $param['seaTime'].'-12-31 23:59:59';
			}
			$start_time_l = strtotime($start_time);
			$end_time_l = strtotime($end_time);
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;
			$order = DB::name("order")
			->where('c_time','between',[$start_time_l,$end_time_l])
			->where("delete_status",0)->column('m_id');

			$school = DB::name("school_specialty")->where([
				"pid"=>0,'is_class'=>0
			])->field('id,pid,name')->limit($offset,$limit)->select();
			$return['total'] = DB::name("school_specialty")->where([
				"pid"=>0,'is_class'=>0
			])->count();
			$data = [];
			$return['sum0'] = 0;
			$return['sum1'] = 0;
			$return['sum2'] = 0;
			$return['sum3'] = 0;
			$return['sum4'] = 0;
			$return['sum5'] = 0;
			$return['sum6'] = 0;
			$return['sum7'] = 0;
			$return['sum8'] = 0;
			$return['sum9'] = 0;
			foreach($school as $k => $v){
				$url = 'num_price_statistics_grade?school_id='.$v['id'];
				$data[$k]['name'] = "<a class='getTable' data-url='".$url."' href='javascript:;'>".$v['name']."</a>";
				// 人数
				$num_ing = DB::name('student')->where([
					'school_id' => $v['id'],
					'm_id' => ['in',$order],
					'school_roll' => 1,
					'delete_status' => 0
				])->count();
				$num_end = DB::name('student')->where([
					'school_id' => $v['id'],
					'm_id' => ['in',$order],
					'school_roll' => 2,
					'delete_status' => 0
				])->count();
				$num_stop = DB::name('student')->where([
					'school_id' => $v['id'],
					'm_id' => ['in',$order],
					'school_roll' => 3,
					'delete_status' => 0
				])->count();
				$num_out = DB::name('student')->where([
					'school_id' => $v['id'],
					'm_id' => ['in',$order],
					'school_roll' => 4,
					'delete_status' => 0
				])->count();
				$data[$k]['num_ing'] = $num_ing;
				$data[$k]['num_end'] = $num_end;
				$data[$k]['num_stop'] = $num_stop;
				$data[$k]['num_out'] = $num_out;
				$data[$k]['num_total'] = $num_ing + $num_end + $num_stop + $num_out;
				// 金额
				$money_1 = DB::name("order")->where([
					"school_id" => $v['id'],
					'delete_status' => 0
				])->where('c_time','between',[$start_time_l,$end_time_l])
				->sum('tuition');
				$money_2 = DB::name("order")->where([
					"school_id" => $v['id'],
					'delete_status' => 0
				])->where('c_time','between',[$start_time_l,$end_time_l])
				->sum('registration');
				$money_3 = DB::name("order")->where([
					"school_id" => $v['id'],
					'delete_status' => 0
				])->where('c_time','between',[$start_time_l,$end_time_l])
				->sum('material_cost');
				$money_4 = DB::name("order")->where([
					"school_id" => $v['id'],
					'delete_status' => 0
				])->where('c_time','between',[$start_time_l,$end_time_l])
				->sum('photo_collection');
				$data[$k]['tuition'] = $money_1;
				$data[$k]['registration'] = $money_2;
				$data[$k]['material_cost'] = $money_3;
				$data[$k]['photo_collection'] = $money_4;
				$data[$k]['money_total'] = $money_1 + $money_2 + $money_3 + $money_4;
				$return['sum0'] += $num_ing;
				$return['sum1'] += $num_end;
				$return['sum2'] += $num_stop;
				$return['sum3'] += $num_out;
				$return['sum4'] += $num_ing + $num_end + $num_stop + $num_out;
				$return['sum5'] += $money_1;
				$return['sum6'] += $money_2;
				$return['sum7'] += $money_3;
				$return['sum8'] += $money_4;
				$return['sum9'] += $money_1 + $money_2 + $money_3 + $money_4;
			}
			$return['rows'] = $data;
			return $return;
		}
		return $this->fetch();
	}

	public function num_price_statistics_grade(){
		$param = input();
		$start_time = $param['seaTime']."-01-01 00:00:00";
		$end_time = $param['seaTime'].'-12-31 23:59:59';
		$start_time_l = strtotime($start_time);
		$end_time_l = strtotime($end_time);
		$limit = $param['pageSize'];
		$offset = ($param['pageNumber'] - 1) * $limit;
		$grade = DB::name('product_attr')->where('pid',1)->limit($limit,$offset)->select();
		$return = [];
		$return["total"] = DB::name('product_attr')->where('pid',1)->count();
		$order = DB::name("order")
		->where('c_time','between',[$start_time_l,$end_time_l])
		->where('delete_status',0)->column('m_id');
		$data = [];
		$return['sum0'] = 0;
		$return['sum1'] = 0;
		$return['sum2'] = 0;
		$return['sum3'] = 0;
		$return['sum4'] = 0;
		$return['sum5'] = 0;
		$return['sum6'] = 0;
		$return['sum7'] = 0;
		$return['sum8'] = 0;
		$return['sum9'] = 0;
		foreach($grade as $k => $v){
			$url = 'num_price_statistics_major?school_id='.$param['school_id'];
			$url .= "&grade=".$v['id'];
			$data[$k]['name'] = "<a class='getTable' data-url='".$url."' href='javascript:;'>".$v['name']."</a>";
			$num_ing = DB::name('student')->where([
				'school_id' => $param['school_id'],
				'grade' => $v['id'],
				'm_id' => ['in',$order],
				'school_roll' => 1,
				'delete_status' => 0
			])->count();
			$num_end = DB::name('student')->where([
				'school_id' => $param['school_id'],
				'grade' => $v['id'],
				'm_id' => ['in',$order],
				'school_roll' => 2,
				'delete_status' => 0
			])->count();
			$num_stop = DB::name('student')->where([
				'school_id' => $param['school_id'],
				'grade' => $v['id'],
				'm_id' => ['in',$order],
				'school_roll' => 3,
				'delete_status' => 0
			])->count();
			$num_out = DB::name('student')->where([
				'school_id' => $param['school_id'],
				'grade' => $v['id'],
				'm_id' => ['in',$order],
				'school_roll' => 4,
				'delete_status' => 0
			])->count();
			$data[$k]['num_ing'] = $num_ing;
			$data[$k]['num_end'] = $num_end;
			$data[$k]['num_stop'] = $num_stop;
			$data[$k]['num_out'] = $num_out;
			$data[$k]['num_total'] = $num_ing + $num_end + $num_stop + $num_out;
			// 金额
			$money_1 = DB::name("order")->where([
				"school_id" => $param['school_id'],
				"grade" => $v['id'],
				'delete_status' => 0
			])->where('c_time','between',[$start_time_l,$end_time_l])
			->sum('tuition');
			$money_2 = DB::name("order")->where([
				"school_id" => $param['school_id'],
				"grade" => $v['id'],
				'delete_status' => 0
			])->where('c_time','between',[$start_time_l,$end_time_l])
			->sum('registration');
			$money_3 = DB::name("order")->where([
				"school_id" => $param['school_id'],
				"grade" => $v['id'],
				'delete_status' => 0
			])->where('c_time','between',[$start_time_l,$end_time_l])
			->sum('material_cost');
			$money_4 = DB::name("order")->where([
				"school_id" => $param['school_id'],
				"grade" => $v['id'],
				'delete_status' => 0
			])->where('c_time','between',[$start_time_l,$end_time_l])
			->sum('photo_collection');
			$data[$k]['tuition'] = $money_1;
			$data[$k]['registration'] = $money_2;
			$data[$k]['material_cost'] = $money_3;
			$data[$k]['photo_collection'] = $money_4;
			$data[$k]['money_total'] = $money_1 + $money_2 + $money_3 + $money_4;
			if($num_ing + $num_end + $num_stop + $num_out == 0){
				$return['total'] -= 1;
				unset($data[$k]);
			}else{
				$return['sum0'] += $num_ing;
				$return['sum1'] += $num_end;
				$return['sum2'] += $num_stop;
				$return['sum3'] += $num_out;
				$return['sum4'] += $num_ing + $num_end + $num_stop + $num_out;
				$return['sum5'] += $money_1;
				$return['sum6'] += $money_2;
				$return['sum7'] += $money_3;
				$return['sum8'] += $money_4;
				$return['sum9'] += $money_1 + $money_2 + $money_3 + $money_4;
			}
		}
		foreach($data as $v){
			$return["rows"][] = $v;
		}

		return $return;
	}

	public function num_price_statistics_major(){
		$param = input();
		$start_time = $param['seaTime']."-01-01 00:00:00";
		$end_time = $param['seaTime'].'-12-31 23:59:59';
		$start_time_l = strtotime($start_time);
		$end_time_l = strtotime($end_time);
		$limit = $param['pageSize'];
		$offset = ($param['pageNumber'] - 1) * $limit;
		$major = DB::name("school_specialty")->where([
			"pid"=>$param['school_id'],'is_class'=>0
		])->field('id,pid,name')->limit($offset,$limit)->select();
		$return = [];
		$return["total"] = DB::name('product_attr')->where('pid',1)->count();
		$order = DB::name("order")
		->where('c_time','between',[$start_time_l,$end_time_l])
		->where('delete_status',0)->column('m_id');
		$data = [];
		$return['sum0'] = 0;
		$return['sum1'] = 0;
		$return['sum2'] = 0;
		$return['sum3'] = 0;
		$return['sum4'] = 0;
		$return['sum5'] = 0;
		$return['sum6'] = 0;
		$return['sum7'] = 0;
		$return['sum8'] = 0;
		$return['sum9'] = 0;
		foreach($major as $k => $v){
			$url = 'num_price_statistics_st?school_id='.$param['school_id'];
			$url .= "&grade=".$param['grade'];
			$url .= "&major_id=".$v['id'];
			$data[$k]['name'] = "<a class='getST' data-url='".$url."' href='javascript:;'>".$v['name']."</a>";
			$num_ing = DB::name('student')->where([
				'school_id' => $param['school_id'],
				'major_id' => $v['id'],
				'grade' => $param['grade'],
				'm_id' => ['in',$order],
				'school_roll' => 1,
				'delete_status' => 0
			])->count();
			$num_end = DB::name('student')->where([
				'school_id' => $param['school_id'],
				'major_id' => $v['id'],
				'grade' => $param['grade'],
				'm_id' => ['in',$order],
				'school_roll' => 2,
				'delete_status' => 0
			])->count();
			$num_stop = DB::name('student')->where([
				'school_id' => $param['school_id'],
				'major_id' => $v['id'],
				'grade' => $param['grade'],
				'm_id' => ['in',$order],
				'school_roll' => 3,
				'delete_status' => 0
			])->count();
			$num_out = DB::name('student')->where([
				'school_id' => $param['school_id'],
				'major_id' => $v['id'],
				'grade' => $param['grade'],
				'm_id' => ['in',$order],
				'school_roll' => 4,
				'delete_status' => 0
			])->count();
			$data[$k]['num_ing'] = $num_ing;
			$data[$k]['num_end'] = $num_end;
			$data[$k]['num_stop'] = $num_stop;
			$data[$k]['num_out'] = $num_out;
			$data[$k]['num_total'] = $num_ing + $num_end + $num_stop + $num_out;
			// 金额
			$money_1 = DB::name("order")->where([
				"school_id" => $param['school_id'],
				'major_id' => $v['id'],
				"grade" => $param['grade'],
				'delete_status' => 0
			])->where('c_time','between',[$start_time_l,$end_time_l])
			->sum('tuition');
			$money_2 = DB::name("order")->where([
				"school_id" => $param['school_id'],
				'major_id' => $v['id'],
				"grade" => $param['grade'],
				'delete_status' => 0
			])->where('c_time','between',[$start_time_l,$end_time_l])
			->sum('registration');
			$money_3 = DB::name("order")->where([
				"school_id" => $param['school_id'],
				'major_id' => $v['id'],
				"grade" => $param['grade'],
				'delete_status' => 0
			])->where('c_time','between',[$start_time_l,$end_time_l])
			->sum('material_cost');
			$money_4 = DB::name("order")->where([
				"school_id" => $param['school_id'],
				'major_id' => $v['id'],
				"grade" => $param['grade'],
				'delete_status' => 0
			])->where('c_time','between',[$start_time_l,$end_time_l])
			->sum('photo_collection');
			$data[$k]['tuition'] = $money_1;
			$data[$k]['registration'] = $money_2;
			$data[$k]['material_cost'] = $money_3;
			$data[$k]['photo_collection'] = $money_4;
			$data[$k]['money_total'] = $money_1 + $money_2 + $money_3 + $money_4;
			if($num_ing + $num_end + $num_stop + $num_out == 0){
				$return['total'] -= 1;
				unset($data[$k]);
			}else{
				$return['sum0'] += $num_ing;
				$return['sum1'] += $num_end;
				$return['sum2'] += $num_stop;
				$return['sum3'] += $num_out;
				$return['sum4'] += $num_ing + $num_end + $num_stop + $num_out;
				$return['sum5'] += $money_1;
				$return['sum6'] += $money_2;
				$return['sum7'] += $money_3;
				$return['sum8'] += $money_4;
				$return['sum9'] += $money_1 + $money_2 + $money_3 + $money_4;
			}
		}
		foreach($data as $v){
			$return["rows"][] = $v;
		}
		return $return;
	}

	public function num_price_statistics_st(){
		$param = input();
		$start_time = $param['seaTime']."-01-01 00:00:00";
		$end_time = $param['seaTime'].'-12-31 23:59:59';
		$start_time_l = strtotime($start_time);
		$end_time_l = strtotime($end_time);
		$limit = $param['pageSize'];
		$offset = ($param['pageNumber'] - 1) * $limit;
		$order = DB::name("order")
		->where('c_time','between',[$start_time_l,$end_time_l])
		->where('delete_status',0)->column('m_id');
		$st = DB::name("student")->where([
			'school_id' => $param['school_id'],
			'major_id' => $param['major_id'],
			'grade' => $param['grade'],
			'm_id' => ['in',$order],
			'batch' => ['like',"%".$param['seaBatch']."%"],
			'delete_status' => 0
		])->limit($offset,$limit)->select();
		$reutrn = [];
		$return['total'] = DB::name("student")->where([
			'school_id' => $param['school_id'],
			'major_id' => $param['major_id'],
			'grade' => $param['grade'],
			'm_id' => ['in',$order],
			'batch' => ['like',"%".$param['seaBatch']."%"],
			'delete_status' => 0
		])->count();
		$data = [];
		foreach($st as$k => $v){
			$oInfo = DB::name("order")->where('m_id',$v['m_id'])
			->where("delete_status",0)->find();
			$url = url("member/memberinfo",['m_id'=>$v['m_id']]);
			$data[$k]['name'] = "<a href='".$url."'>".$v['name']."</a>";
			$data[$k]['batch'] = $v['batch'];
			$data[$k]['money_total'] = $oInfo['total_amount'];
			$data[$k]['tuition'] = $oInfo['tuition'];
			$data[$k]['registration'] = $oInfo['registration'];
			$data[$k]['material_cost'] = $oInfo['material_cost'];
			$data[$k]['photo_collection'] = $oInfo['photo_collection'];
		}
		$return['rows'] = $data;
		return $return;
	}

	public function NumMoneyStatisticsExportAll(){
		$param = input();
		$start_time = $param['seaTime']."-01-01 00:00:00";
		$end_time = $param['seaTime'].'-12-31 23:59:59';
		$start_time_l = strtotime($start_time);
		$end_time_l = strtotime($end_time);
		$order = DB::name("order")
		->where('c_time','between',[$start_time_l,$end_time_l])
		->where("delete_status",0)->column('m_id');
		$st = DB::name("student")->where([
			'school_id' => $param['school_id'],
			'major_id' => $param['major_id'],
			'grade' => $param['grade'],
			'm_id' => ['in',$order],
			'delete_status' => 0
		])->select();
		$data = [];
		foreach($st as$k => $v){
			$oInfo = DB::name("order")->where('m_id',$v['m_id'])->find();
			$data[$k]['name'] = $v['name'];
			$data[$k]['batch'] = $v['batch'];
			$data[$k]['money_total'] = $oInfo['total_amount'];
			$data[$k]['tuition'] = $oInfo['tuition'];
			$data[$k]['registration'] = $oInfo['registration'];
			$data[$k]['material_cost'] = $oInfo['material_cost'];
			$data[$k]['photo_collection'] = $oInfo['photo_collection'];
		}
		$savePath = explode('../application/',APP_PATH)[0].'upload/excel/';
		$title = [
			'姓名',
			'批次',
			'总计',
			'学费',
			'报名费',
			'资料费',
			'照片采集费'
		];
		$this->exportExcel($title,$data, 'download_finance_num', $savePath, false);
	}
}
